<!--历史数据-->
<template>
  <div class="ele-body">
    <!-- 搜索表单 -->
    <div class="block-interval">
      <a-card :bordered="false">
        <a-form layout="inline" :model="where">
          <a-row>

            <a-form-item label="开始时间:">
              <a-date-picker v-model:value="where.searchBeginTime" type="date" show-time format="YYYY-MM-DD HH:mm:ss" valueFormat="YYYY-MM-DD HH:mm:ss" />
            </a-form-item>
            <a-form-item label="结束时间:">
              <a-date-picker v-model:value="where.searchEndTime" type="date" show-time format="YYYY-MM-DD HH:mm:ss" valueFormat="YYYY-MM-DD HH:mm:ss" />
            </a-form-item>

            <a-form-item class="ele-text-center">
              <a-space>
                <a-button type="primary" @click="reload">查询</a-button>
                <a-button @click="reset">重置</a-button>
                <a-button @click="downloadFile">下载</a-button>
              </a-space>
            </a-form-item>

          </a-row>
        </a-form>
      </a-card>

      <a-card
        :bordered="false"
        title="瘤胃温度和牛舍环境数据关系图"
        :body-style="{padding: '16px 6px 0 0'}">
        <v-chart
          ref="tempEnvDataChart"
          style="height: 362px;"
          :option="tempEnvDataChartOption"/>
      </a-card>

    </div>

    <!-- 表格 -->
    <div>
      <a-card :bordered="false">
        <ele-pro-table
          ref="table"
          row-key="cattleTemperId"
          :datasource="datasource"
          :columns="columns"
          :where="where"
          v-model:selection="selection"
          :scroll="{ x: 'max-content' }"
        >

          <template #bodyCell="{ column, record }">
            <!-- table操作栏按钮 -->
            <template v-if="column.key === 'action'">
              <a-space>
                <a-popconfirm title="确定要删除此记录吗？" @confirm="remove(record)">
                  <a class="ele-text-danger">删除</a>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>
  </div>
</template>

<script>
import { provide } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart, BarChart } from 'echarts/charts';
import {
  GridComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components';
import VChart, { THEME_KEY } from 'vue-echarts';
import 'echarts-wordcloud';
import { ChartTheme } from 'ele-admin-pro';
import moment from 'moment'
import {CattleTemperatureDataApi} from '@/api/property/cattlemanager/CattleTemperatureDataApi';
import { message } from 'ant-design-vue';
import {SysDatadownLogApi} from "@/api/system/operation/SysDatadownLogApi";
import {OxtallEnvDataApi} from "@/api/property/OxtallEnvDataApi";
import {CattleHeartbeatDataApi} from "@/api/property/cattlemanager/CattleHeartbeatDataApi";
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent
]);

provide(THEME_KEY, ChartTheme);

export default {
  name: 'CattleManagerCattlehealthdataTemperatureData',
  components: {
    VChart
  },
  props: {
    data: Object
  },
  async mounted() {
    this.getTempEnvData();
  },
  data() {
    return {
      // 表格列配置
      columns: [
        {
          title: '温度计序列号',
          dataIndex: 'thermNo'
        },
        {
          title: '实时瘤胃温度',
          dataIndex: 'bodyTemperature'
        },
        {
          title: '采集时间',
          dataIndex: 'uploadTime'
        },
        {
          title: '操作',
          key: 'action',
          width: 280,
          align: 'center'
        }
      ],
      // 表格搜索条件
      where: {
        cattleId : this.data.cattleId
      },
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
      tempEnvData : [],
    };
  },
  computed: {
    //呼吸速率
    tempEnvDataChartOption() {
      return {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['瘤胃温度', '牛舍温度', '牛舍湿度', '牛舍氨气浓度', '牛呼吸速率', '牛心跳速率'],
          right: 20
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: this.tempEnvData.time
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '瘤胃温度',
            type: 'line',
            showSymbol: false,
            data: this.tempEnvData.bodyTemp,
            connectNulls: true
          },
          {
            name: '牛舍温度',
            type: 'line',
            showSymbol: false,
            data: this.tempEnvData.temp,
            connectNulls: true
          },
          {
            name: '牛舍湿度',
            type: 'line',
            showSymbol: false,
            data: this.tempEnvData.humidity,
            connectNulls: true
          },
          {
            name: '牛舍氨气浓度',
            type: 'line',
            showSymbol: false,
            data: this.tempEnvData.nhthree,
            connectNulls: true
          },
          {
            name: '牛呼吸速率',
            type: 'line',
            showSymbol: false,
            data: this.tempEnvData.respirationRate,
            connectNulls: true
          },
          {
            name: '牛心跳速率',
            type: 'line',
            showSymbol: false,
            data: this.tempEnvData.heartRate,
            connectNulls: true
          }
        ]
      }
    },
  },
  methods: {
    getTempEnvData() {
      let params = {
        searchBeginTime : moment().subtract(1, 'h').format('YYYY-MM-DD HH:mm:ss'),
        searchEndTime : moment().format('YYYY-MM-DD HH:mm:ss'),
        cattleId: this.data.cattleId,
        orderBy : "upload_time",
        sortBy : "asc"
      };

      let envParams = {
        searchBeginTime : moment().subtract(1, 'h').format('YYYY-MM-DD HH:mm:ss'),
        searchEndTime : moment().format('YYYY-MM-DD HH:mm:ss'),
        oxtallId: this.data.oxtId,
        orderBy : "create_time",
        sortBy : "asc"
      };

      let heartParams = {
        searchBeginTime : moment().subtract(1, 'h').format('YYYY-MM-DD HH:mm:ss'),
        searchEndTime : moment().format('YYYY-MM-DD HH:mm:ss'),
        cattleId: this.data.cattleId,
        rateStates : "1,2,3",
        orderBy : "create_time",
        sortBy : "asc"
      };

      if (this.where.searchBeginTime && this.where.searchEndTime) {
        params.searchBeginTime = this.where.searchBeginTime;
        params.searchEndTime = this.where.searchEndTime;
        envParams.searchBeginTime = this.where.searchBeginTime;
        envParams.searchEndTime = this.where.searchEndTime;
        heartParams.searchBeginTime = this.where.searchBeginTime;
        heartParams.searchEndTime = this.where.searchEndTime;
      }
      let that = this;
      Promise.all([
        CattleTemperatureDataApi.list(params),
        OxtallEnvDataApi.list(envParams),
        CattleHeartbeatDataApi.list(heartParams)
      ]).then(function (resArr){
        let cattleTemperatureData = resArr[0];
        let oxtallEnvData = resArr[1];
        let heartBData = resArr[2];
        that.tempEnvData = {
          "bodyTemp" : [],
          "temp" : [],
          "humidity" : [],
          "nhthree" : [],
          "time": [],
          "respirationRate" : [],
          "heartRate" : [],
        };

        let last20 = moment().subtract(20, 'minute');
        let last10 = moment().subtract(10, 'minute');
        let last5 = moment().subtract(5, 'minute');

        if (cattleTemperatureData && cattleTemperatureData.length > 0) {
          cattleTemperatureData.forEach(function(item) {
            that.tempEnvData.bodyTemp.push([item.uploadTime, item.bodyTemperature]);
            if (!that.tempEnvData.time.includes(item.uploadTime)) {
              that.tempEnvData.time.push(item.uploadTime);
            }
          });
        } else {
          that.tempEnvData.bodyTemp.push([last20.format('YYYY-MM-DD HH:mm:ss'), 0]);
          that.tempEnvData.bodyTemp.push([last10.format('YYYY-MM-DD HH:mm:ss'), 0]);
          that.tempEnvData.bodyTemp.push([last5.format('YYYY-MM-DD HH:mm:ss'), 0]);
          that.tempEnvData.time.push(last20.format('YYYY-MM-DD HH:mm:ss'));
          that.tempEnvData.time.push(last10.format('YYYY-MM-DD HH:mm:ss'));
          that.tempEnvData.time.push(last5.format('YYYY-MM-DD HH:mm:ss'));
        }

        if (oxtallEnvData && oxtallEnvData.length > 0) {
          oxtallEnvData.forEach(function(item) {
            that.tempEnvData.temp.push([item.createTime, item.temperature]);
            that.tempEnvData.humidity.push([item.createTime, item.humidity]);
            that.tempEnvData.nhthree.push([item.createTime, item.nhthree]);
            if (!that.tempEnvData.time.includes(item.createTime)) {
              that.tempEnvData.time.push(item.createTime);
            }
          });
        } else {
          that.tempEnvData.temp.push([last20.format('YYYY-MM-DD HH:mm:ss'), 0]);
          that.tempEnvData.temp.push([last10.format('YYYY-MM-DD HH:mm:ss'), 0]);
          that.tempEnvData.temp.push([last5.format('YYYY-MM-DD HH:mm:ss'), 0]);

          that.tempEnvData.humidity.push([last20.format('YYYY-MM-DD HH:mm:ss'), 0]);
          that.tempEnvData.humidity.push([last10.format('YYYY-MM-DD HH:mm:ss'), 0]);
          that.tempEnvData.humidity.push([last5.format('YYYY-MM-DD HH:mm:ss'), 0]);

          that.tempEnvData.nhthree.push([last20.format('YYYY-MM-DD HH:mm:ss'), 0]);
          that.tempEnvData.nhthree.push([last10.format('YYYY-MM-DD HH:mm:ss'), 0]);
          that.tempEnvData.nhthree.push([last5.format('YYYY-MM-DD HH:mm:ss'), 0]);

          if (!that.tempEnvData.time.includes(last20.format('YYYY-MM-DD HH:mm:ss'))) {
            that.tempEnvData.time.push(last20.format('YYYY-MM-DD HH:mm:ss'));
          }
          if (!that.tempEnvData.time.includes(last10.format('YYYY-MM-DD HH:mm:ss'))) {
            that.tempEnvData.time.push(last10.format('YYYY-MM-DD HH:mm:ss'));
          }
          if (!that.tempEnvData.time.includes(last5.format('YYYY-MM-DD HH:mm:ss'))) {
            that.tempEnvData.time.push(last5.format('YYYY-MM-DD HH:mm:ss'));
          }
        }

        if (heartBData && heartBData.length > 0) {
          let split = 0;
          if (heartBData.length > 120 && heartBData.length < 180) {
            split = 9;
          } else if (heartBData.length > 180 && heartBData.length < 300) {
            split = 15;
          } else if (heartBData.length > 300 && heartBData.length < 1000) {
            split = 35;
          } else if (heartBData.length > 1000 && heartBData.length < 3000) {
            split = 100;
          } else if (heartBData.length > 3000) {
            split = 400;
          }
          let i = 0;
          heartBData.forEach(function (item) {
            if (split == 0) {
              that.tempEnvData.respirationRate.push([item.createTime, item.respirationRate]);
              that.tempEnvData.heartRate.push([item.createTime, item.heartRate]);
              if (!that.tempEnvData.time.includes(item.createTime)) {
                that.tempEnvData.time.push(item.createTime);
              }
            } else if (split > 0 && i % split == 0) {
              that.tempEnvData.respirationRate.push([item.createTime, item.respirationRate]);
              that.tempEnvData.heartRate.push([item.createTime, item.heartRate]);
              if (!that.tempEnvData.time.includes(item.createTime)) {
                that.tempEnvData.time.push(item.createTime);
              }
            }
            i++;
          });
        } else {
          that.tempEnvData.respirationRate.push([last20.format('YYYY-MM-DD HH:mm:ss'), 0]);
          that.tempEnvData.respirationRate.push([last10.format('YYYY-MM-DD HH:mm:ss'), 0]);
          that.tempEnvData.respirationRate.push([last5.format('YYYY-MM-DD HH:mm:ss'), 0]);

          that.tempEnvData.heartRate.push([last20.format('YYYY-MM-DD HH:mm:ss'), 0]);
          that.tempEnvData.heartRate.push([last10.format('YYYY-MM-DD HH:mm:ss'), 0]);
          that.tempEnvData.heartRate.push([last5.format('YYYY-MM-DD HH:mm:ss'), 0]);

          if (!that.tempEnvData.time.includes(last20.format('YYYY-MM-DD HH:mm:ss'))) {
            that.tempEnvData.time.push(last20.format('YYYY-MM-DD HH:mm:ss'));
          }
          if (!that.tempEnvData.time.includes(last10.format('YYYY-MM-DD HH:mm:ss'))) {
            that.tempEnvData.time.push(last10.format('YYYY-MM-DD HH:mm:ss'));
          }
          if (!that.tempEnvData.time.includes(last5.format('YYYY-MM-DD HH:mm:ss'))) {
            that.tempEnvData.time.push(last5.format('YYYY-MM-DD HH:mm:ss'));
          }
        }

        that.tempEnvData.time.sort();
      })
    },
    /**
     * 搜索按钮
     *
     * @author cancan
     * @date 2023/03/18 20:10
     */
    reload() {
      this.selection = [];
      this.$refs.table.reload({page: 1});
      this.getTempEnvData();
    },

    /**
     * 重置搜索
     *
     * @author cancan
     * @date 2023/03/18 20:10
     */
    reset() {
      this.where.cattleId = this.data.cattleId;
      this.where.searchBeginTime = '';
      this.where.searchEndTime = '';
      this.$nextTick(() => {
        this.reload();
      });
    },

    /**
     * 删除
     *
     * @author cancan
     * @date 2023/03/18 20:10
     */
    async remove(row) {
      const result = await CattleTemperatureDataApi.delete({cattleTemperId: row.cattleTemperId});
      message.success(result.message);
      this.reload();
    },

    datasource({ page, limit, where, orders }) {
      return CattleTemperatureDataApi.findPage({ ...where, ...orders, pageNo: page, pageSize: limit });
    },
    activated() {
      ['tempEnvDataChart'].forEach((name) => {
        this.$refs[name].resize();
      });
    },
    downloadFile () {
      if (this.where.searchBeginTime && this.where.searchEndTime) {
        let fromParam = {
          "searchBeginTime" : this.where.searchBeginTime,
          "searchEndTime" : this.where.searchEndTime,
          "cattleId" : this.data.cattleId + "",
        };
        let from = {
          "downName" : "奶牛id为"+this.data.cattleId+"的瘤胃温度数据下载",
          "downScene" : 4,
          "downCondition" : JSON.stringify(fromParam)
        };

        let result = SysDatadownLogApi.add(from);
        result
          .then(result1 => {
            message.success("添加下载任务成功，请移步到【数据下载】->【导出记录】查看")
          })
          .catch(() => {
          });
      } else {
        message.warn("请选择时间条件");
      }
    },
  }
};
</script>
